/**
 * WebSocket连接管理类
 */
export class SocketManager {
  constructor(url = 'wss://api.fcoin.com/v2/ws', options = {}) {
    this.url = url
    this.options = options
    this.socket = null
    this.connState = 0 // 0: 未连接, 1: 连接中, 2: 已连接
    this.messageMap = {}
    this.heartBeatTimer = null
    this.reconnectTimer = null
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.afterOpenEmit = []
  }

  /**
   * 建立连接
   */
  doOpen() {
    if (this.connState) return

    console.log('正在连接WebSocket:', this.url)
    this.connState = 1
    this.afterOpenEmit = []

    const BrowserWebSocket = window.WebSocket || window.MozWebSocket
    this.socket = new BrowserWebSocket(this.url)
    this.socket.binaryType = 'arraybuffer'

    this.socket.onopen = (evt) => this.onOpen(evt)
    this.socket.onclose = (evt) => this.onClose(evt)
    this.socket.onmessage = (evt) => this.onMessage(evt.data)
    this.socket.onerror = (err) => this.onError(err)
  }

  /**
   * 连接成功回调
   */
  onOpen(evt) {
    console.log('WebSocket连接成功')
    this.connState = 2
    this.reconnectAttempts = 0
    
    // 开始心跳检测
    this.heartBeatTimer = setInterval(() => {
      this.checkHeartbeat()
    }, 20000)

    this.onReceiver({ Event: 'open' })
  }

  /**
   * 检查连接状态
   */
  checkOpen() {
    return this.connState === 2
  }

  /**
   * 连接关闭回调
   */
  onClose(evt) {
    console.log('WebSocket连接关闭:', evt)
    this.connState = 0
    
    if (this.heartBeatTimer) {
      clearInterval(this.heartBeatTimer)
      this.heartBeatTimer = null
    }

    this.onReceiver({ Event: 'close' })

    // 自动重连
    this.attemptReconnect()
  }

  /**
   * 尝试重连
   */
  attemptReconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.log('重连次数已达上限，停止重连')
      return
    }

    this.reconnectAttempts++
    const delay = Math.pow(2, this.reconnectAttempts) * 1000 // 指数退避

    console.log(`${delay / 1000}秒后进行第${this.reconnectAttempts}次重连...`)
    
    this.reconnectTimer = setTimeout(() => {
      this.doOpen()
    }, delay)
  }

  /**
   * 发送消息
   */
  send(data) {
    if (this.checkOpen()) {
      this.socket.send(JSON.stringify(data))
    } else {
      console.warn('WebSocket未连接，消息发送失败:', data)
    }
  }

  /**
   * 发送消息并返回Promise
   */
  emit(data) {
    return new Promise((resolve) => {
      this.send(data)
      this.on('message', (data) => {
        resolve(data)
      })
    })
  }

  /**
   * 处理接收到的消息
   */
  onMessage(message) {
    try {
      const data = JSON.parse(message)
      this.onReceiver({ Event: 'message', Data: data })
    } catch (err) {
      console.error('数据解析错误:', err)
    }
  }

  /**
   * 心跳检测
   */
  checkHeartbeat() {
    const data = {
      cmd: 'ping',
      args: [Date.parse(new Date())]
    }
    this.send(data)
  }

  /**
   * 错误处理
   */
  onError(err) {
    console.error('WebSocket错误:', err)
    this.onReceiver({ Event: 'error', Data: err })
  }

  /**
   * 消息接收处理器
   */
  onReceiver(data) {
    const callback = this.messageMap[data.Event]
    if (callback) {
      callback(data.Data)
    }
  }

  /**
   * 监听事件
   */
  on(name, handler) {
    this.messageMap[name] = handler
  }

  /**
   * 关闭连接
   */
  doClose() {
    if (this.socket) {
      this.socket.close()
    }
  }

  /**
   * 销毁连接
   */
  destroy() {
    // 清理定时器
    if (this.heartBeatTimer) {
      clearInterval(this.heartBeatTimer)
      this.heartBeatTimer = null
    }
    
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer)
      this.reconnectTimer = null
    }

    // 关闭连接
    this.doClose()
    
    // 清理状态
    this.messageMap = {}
    this.connState = 0
    this.socket = null
    this.reconnectAttempts = 0
  }
} 